package com.code.common.exception;


import com.code.common.vo.ResultData;
import org.apache.shiro.ShiroException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    // 捕捉shiro的异常
     @ExceptionHandler(ShiroException.class)
    public ResultData handle401() {
        return new ResultData().fail(401,"您没有权限访问！",null);
    }


    // 捕捉其他所有异常
    @ExceptionHandler(Exception.class)
    public ResultData globalException(HttpServletRequest request, Throwable ex) {
        return new ResultData().fail(getStatus(request).value(),"访问出错，无法访问: " + ex.getMessage(),null);
    }


    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }


}
